<template>
  <div class="carousel-list">
    <el-card>
      <template #header>
        <div class="card-header">
          <div class="card-header__titles">
            <h1 class="card-title">{{ pageTitle || '轮播图管理' }}</h1>
            <p v-if="pageSubtitle" class="card-subtitle">{{ pageSubtitle }}</p>
          </div>
          <el-button type="primary" @click="showEditDialog()">
            <el-icon><Plus /></el-icon>
            添加轮播图
          </el-button>
        </div>
      </template>

      <!-- 表格 -->
      <el-table
        v-loading="loading"
        :data="carousels"
        border
        stripe
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />

        <el-table-column label="预览" width="200">
          <template #default="{ row }">
            <ImagePreview
              v-if="row.image_url"
              :src="row.image_url"
              width="180px"
              height="60px"
              fit="cover"
            />
          </template>
        </el-table-column>

        <el-table-column label="标题 (EN)" min-width="150">
          <template #default="{ row }">
            {{ getTranslation(row, 'en')?.title || '-' }}
          </template>
        </el-table-column>

        <el-table-column label="副标题 (EN)" min-width="200">
          <template #default="{ row }">
            {{ getTranslation(row, 'en')?.subtitle || '-' }}
          </template>
        </el-table-column>

        <el-table-column prop="sort_order" label="排序" width="100" sortable />

        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.is_active ? 'success' : 'info'">
              {{ row.is_active ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="showEditDialog(row)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button
              size="small"
              :type="row.is_active ? 'warning' : 'success'"
              @click="toggleActive(row)"
            >
              {{ row.is_active ? '禁用' : '启用' }}
            </el-button>
            <el-button
              size="small"
              type="danger"
              @click="handleDelete(row)"
            >
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="editingItem?.id ? '编辑轮播图' : '添加轮播图'"
      width="800px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="formRef"
        :model="formData"
        label-width="120px"
      >
        <!-- 图片上传 -->
        <el-form-item label="轮播图图片" required>
          <el-upload
            class="carousel-uploader"
            :show-file-list="false"
            :on-change="handleImageChange"
            :auto-upload="false"
            accept="image/*"
          >
            <img v-if="imagePreview || editingItem?.image_url" :src="imagePreview || editingItem?.image_url" class="carousel-image" />
            <el-icon v-else class="carousel-uploader-icon"><Plus /></el-icon>
          </el-upload>
          <div class="form-hint">建议尺寸：1920x600px</div>
        </el-form-item>

        <!-- 链接 -->
        <el-form-item label="链接地址">
          <el-input
            v-model="formData.link"
            placeholder="例如：/products 或 https://example.com"
          />
        </el-form-item>

        <!-- 排序 -->
        <el-form-item label="排序" required>
          <el-input-number v-model="formData.sort_order" :min="0" />
        </el-form-item>

        <!-- 状态 -->
        <el-form-item label="状态">
          <el-switch v-model="formData.is_active" />
        </el-form-item>

        <!-- 多语言内容 -->
        <el-divider content-position="left">多语言内容</el-divider>

        <el-tabs v-model="activeLocale">
          <el-tab-pane
            v-for="locale in locales"
            :key="locale.code"
            :label="locale.name"
            :name="locale.code"
          >
            <el-form-item label="标题">
              <el-input v-model="getTranslationData(locale.code).title" />
            </el-form-item>

            <el-form-item label="副标题">
              <el-input v-model="getTranslationData(locale.code).subtitle" />
            </el-form-item>

            <el-form-item label="按钮文字">
              <el-input v-model="getTranslationData(locale.code).cta_text" />
            </el-form-item>
          </el-tab-pane>
        </el-tabs>
      </el-form>

      <template #footer>
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
          保存
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Edit, Delete } from '@element-plus/icons-vue'
import { getCarousels, createCarousel, updateCarousel, deleteCarousel, toggleCarouselActive, type Carousel, type CarouselTranslation } from '@/api/carousel'
import ImagePreview from '@/components/ImagePreview.vue'
import { usePageMeta } from '@/composables/usePageMeta'

const carousels = ref<Carousel[]>([])
const dialogVisible = ref(false)
const editingItem = ref<Carousel | null>(null)
const loading = ref(false)
const submitLoading = ref(false)
const imagePreview = ref('')
const imageFile = ref<File | null>(null)
const activeLocale = ref('en')

const locales = [
  { code: 'en', name: 'English' },
  { code: 'zh', name: '中文' },
  { code: 'nl', name: 'Nederlands' },
  { code: 'de', name: 'Deutsch' },
  { code: 'fr', name: 'Français' }
]

const { pageTitle, pageSubtitle } = usePageMeta()

const formData = ref({
  link: '',
  sort_order: 0,
  is_active: true,
  translations: [] as CarouselTranslation[]
})

const loadCarousels = async () => {
  loading.value = true
  try {
    const response = await getCarousels() as any
    carousels.value = response.results || response
  } catch (error) {
    console.error('Failed to load carousels:', error)
    ElMessage.error('加载轮播图列表失败')
  } finally {
    loading.value = false
  }
}

const getTranslation = (item: Carousel, locale: string) => {
  return item.translations?.find(t => t.locale === locale)
}

const getTranslationData = (locale: string) => {
  let translation = formData.value.translations.find(t => t.locale === locale)
  if (!translation) {
    translation = { locale, title: '', subtitle: '', cta_text: '' }
    formData.value.translations.push(translation)
  }
  return translation
}

const showEditDialog = (item?: Carousel) => {
  editingItem.value = item || null
  imagePreview.value = ''
  imageFile.value = null
  activeLocale.value = 'en'

  if (item) {
    formData.value = {
      link: item.link || '',
      sort_order: item.sort_order,
      is_active: item.is_active,
      translations: JSON.parse(JSON.stringify(item.translations || []))
    }
  } else {
    formData.value = {
      link: '',
      sort_order: 0,
      is_active: true,
      translations: []
    }
  }

  dialogVisible.value = true
}

const closeDialog = () => {
  dialogVisible.value = false
  editingItem.value = null
  imagePreview.value = ''
  imageFile.value = null
}

const handleImageChange = (file: any) => {
  imageFile.value = file.raw
  const reader = new FileReader()
  reader.onload = (e) => {
    imagePreview.value = e.target?.result as string
  }
  reader.readAsDataURL(file.raw)
}

const handleSubmit = async () => {
  // 创建时必须上传图片
  if (!imageFile.value && !editingItem.value?.id) {
    ElMessage.warning('请上传轮播图图片')
    return
  }

  submitLoading.value = true
  try {
    const data = new FormData()

    // 只有选择了新图片才添加 image 字段
    if (imageFile.value) {
      data.append('image', imageFile.value)
    }

    data.append('link', formData.value.link)
    data.append('sort_order', formData.value.sort_order.toString())
    data.append('is_active', formData.value.is_active.toString())
    data.append('translations', JSON.stringify(formData.value.translations))

    if (editingItem.value?.id) {
      // 编辑模式
      await updateCarousel(editingItem.value.id, data)
      ElMessage.success('更新成功')
    } else {
      // 创建模式
      await createCarousel(data)
      ElMessage.success('创建成功')
    }

    await loadCarousels()
    closeDialog()
  } catch (error: any) {
    console.error('Failed to save carousel:', error)
    const errorMsg = error?.response?.data?.image?.[0] || error?.response?.data?.detail || '保存失败'
    ElMessage.error(errorMsg)
  } finally {
    submitLoading.value = false
  }
}

const toggleActive = async (item: Carousel) => {
  try {
    await toggleCarouselActive(item.id!)
    ElMessage.success('操作成功')
    await loadCarousels()
  } catch (error) {
    console.error('Failed to toggle active:', error)
    ElMessage.error('操作失败')
  }
}

const handleDelete = async (item: Carousel) => {
  try {
    await ElMessageBox.confirm('确定要删除这个轮播图吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    await deleteCarousel(item.id!)
    ElMessage.success('删除成功')
    await loadCarousels()
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('Failed to delete carousel:', error)
      ElMessage.error('删除失败')
    }
  }
}

onMounted(() => {
  loadCarousels()
})
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: var(--spacing-lg);
}

.card-header__titles {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.card-title {
  margin: 0;
  font-size: var(--font-size-xl);
  font-weight: var(--font-weight-semibold);
  color: var(--color-text-primary);
}

.card-subtitle {
  margin: 0;
  font-size: var(--font-size-sm);
  color: var(--color-text-tertiary);
}

.carousel-uploader {
  width: 100%;
}

.carousel-uploader :deep(.el-upload) {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
  width: 100%;
  height: 200px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.carousel-uploader :deep(.el-upload:hover) {
  border-color: var(--el-color-primary);
}

.carousel-uploader-icon {
  font-size: 28px;
  color: #8c939d;
}

.carousel-image {
  width: 100%;
  height: 200px;
  object-fit: contain;
  display: block;
}

.form-hint {
  color: var(--el-text-color-secondary);
  font-size: 12px;
  margin-top: 8px;
  display: block;
}

/* 修复图片预览弹窗的 z-index 层级问题 */
:deep(.el-image-viewer__wrapper) {
  z-index: 9999 !important;
}

:deep(.el-image-viewer__mask) {
  z-index: 9998 !important;
}
</style>
